package net.bxx2004.pandalib.bukkit.language.application;

import net.bxx2004.pandalib.PandaLib;
import net.bxx2004.pandalib.bukkit.language.abandon.PDialog;
import net.bxx2004.pandalib.bukkit.listener.PListener;
import net.bxx2004.pandalib.bukkit.util.PMath;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.AsyncPlayerChatEvent;

import java.util.ArrayList;
import java.util.List;

/**
    用于玩家与服务器对话
 */
public class PConversation {
    private String question;
    private String answer;
    private List<String> players;
    private PListener listener;
    PDialog dialog;
    private boolean def;
    public PConversation(String question,boolean def){
        this.question =question;
        this.dialog = new PDialog();
        this.players= new ArrayList<>();
        this.def = def;
        this.listener = new PListener(){
            @EventHandler
            public void onChat(AsyncPlayerChatEvent event){
                Player player = event.getPlayer();
                if (players.contains(player.getName())){
                    event.setCancelled(true);
                    if (!event.getMessage().equals("cancel")){
                        answer = event.getMessage();
                    }
                    end(player);
                }
            }
        }.hook(PandaLib.initPlugin.getName());
    }

    public String answer() {
        return answer;
    }

    public String question() {
        return question;
    }

    public boolean isFinish(Player player){
        return !players.contains(player.getName());
    }
    public void start(Player player){
        dialog.createDialog(player.getName());
        dialog.setContent(player.getName(), PMath.toStringList(question.split("<br>")));
        players.add(player.getName());
        if (def){
            dialog.to2(player,player.getName(),5);
        }else {
            dialog.to(player,player.getName());
        }
    }
    public void next(Player player,String question){
        players.add(player.getName());
        dialog.setContent(player.getName(), PMath.toStringList(question.split("<br>")));
        if (def){
            dialog.to2(player,player.getName(),5);
        }else {
            dialog.to(player,player.getName());
        }
    }
    public void cancelTask(){
        listener.unhook();
    }
    public void end(Player player){
        players.remove(player.getName());
    }
}
